import { Request, Response, json } from "express";
import { NextFunction } from "express-serve-static-core";
const express = require("express");
const router = express.Router();
import efetch from "../efetch";
const request = require("request");
const qs = require("querystring");
let rp = require("request-promise");
import jar from "../toughCookie";
import r from "../r";

import * as config from "../../config";

router.get("/hasAuth", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  try {
    const newurl = `${config.beApi}/admin/user/getSelfInfo`;
    const ret = await r(
      {
        url: newurl
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);
    if (jsonRet.code === 200) {
      jsonRet.data = true;
    } else {
      jsonRet.data = false;
    }
    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/ca", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  res.clearCookie("SESSION");
  res.json(true);
});

router.get("/findUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  // SESSION=YTM4YzRhZWItMzcxNS00NGFlLTkzNmQtNDUyY2M2MGViZjcw; path=/; domain=192.168.30.22; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;
  const { code, username, password, verify } = req.body;
  if (process.env.NODE_ENV === "eh") {
    const newurl = "http://api.zqd.com/user/findUser";
    const ret = await rp({
      method: "GET",
      url: newurl,
      jar
    }).pipe(res);
    const jsonRet = JSON.parse(ret);
    res.json(jsonRet);
  }
  try {
    const newurl = `${config.beApi}/admin/user/getSelfInfo`;

    const ret = await r(
      {
        url: newurl
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.post("/login", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { code, username, password, verify } = req.body;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/submitLogin`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          password,
          userAccount: username
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.post("/logout", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { code, username, password, verify } = req.body;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/logout`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({})
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.post("/enroll", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { code, username, password, verify } = req.body;
  try {
    const newurl = `${config.beApi}/user/register`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          code,
          password,
          username
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    if (200 === jsonRet.code) {
      res.json(jsonRet);
    } else {
      res.json(jsonRet);
    }
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/hasUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { username } = req.query;
  if (process.env.NODE_ENV === "eh") {
    try {
      const newurl = "http://api.zqd.com/user/hasUser";
      const ret = await rp({
        method: "GET",
        url: newurl,
        jar,
        qs: {
          username: username
        }
      }).pipe(res);

      const jsonRet = JSON.parse(ret);

      if (jsonRet.code === 200) {
        res.json({
          code: 200,
          data: {},
          msg: "success"
        });
      } else {
        res.json({
          code: 4004,
          data: undefined,
          msg: "has_not_user"
        });
      }
    } catch (e) {}
  }
  try {
    const newurl = `${config.beApi}/user/search`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          code: "string",
          password: "string",
          username: username
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    if (jsonRet.code === 200) {
      res.json({
        code: 200,
        data: {},
        msg: "success"
      });
    } else {
      res.json({
        code: 4004,
        data: undefined,
        msg: "has_not_user"
      });
    }
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.post("/savePwd", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { username, password, code, verify } = req.body;
  try {
    const newurl = `${config.beApi}/user/resetPassword`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          code,
          password,
          username
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/delUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/deleteUser`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          userId: id
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/lockUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/forbidUserById`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          status: 0, // 锁定
          userId: id
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/unLockUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/forbidUserById`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          status: 1, // 锁定
          userId: id
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/resetUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/user/resetPswd`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          userId: id
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/resetGoogleCode", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id } = req.query;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  res.json({ code: 200, data: undefined, msg: "not support" });
  return;
  const newurl = "${config.beApi}/user/resetPassword";
  const ret = await rp({
    method: "POST",
    url: newurl,
    jar,
    body: JSON.stringify({
      id
    })
  }).pipe(res);
  const jsonRet = JSON.parse(ret);
  res.json(jsonRet);
});

router.post("/saveUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { username, password, code, verify } = req.body;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/user/resetPassword`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          code,
          password,
          username
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/selectUser", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const {
    code,
    email,
    name,
    phone,
    uid,
    isKyc1,
    isKyc2,
    level,
    p,
    size
  } = req.query;
  const data: Array<any> = [
    {
      code: "1",
      uid: "qwer",
      phone: "13370277157",
      email: "986177191@qq.com",
      enrollTime: 1542858853,
      name: "上海",
      level: "1",
      isKyc1: "no",
      isKyc2: "yes",
      status: 1
    },
    {
      code: "2",
      uid: "abcdefg",
      phone: "123456",
      email: "986177191@qq.com",
      enrollTime: 1542858853,
      name: "北京",
      level: "2",
      isKyc1: "yes",
      isKyc2: "no",
      status: 1
    },
    {
      code: "2",
      uid: "abcdefg",
      phone: "13370277157",
      email: "986177191@qq.com",
      enrollTime: 1542858853,
      name: "上海",
      level: "0",
      isKyc1: "yes",
      isKyc2: "no",
      status: 1
    }
  ]
    .filter(d => {
      if (!!email) {
        return d.email.includes(email);
      }
      return true;
    })
    .filter(d => {
      if (!!name) {
        return d.name.includes(name);
      }
      return true;
    })
    .filter(d => {
      if (!!phone) {
        return d.phone.includes(phone);
      }
      return true;
    })
    .filter(d => {
      if (!!uid) {
        return d.uid.includes(uid);
      }
      return true;
    })
    .filter(d => {
      if (!!code) {
        return d.code.includes(code);
      }
      return true;
    })
    .filter(d => {
      if (!!level) {
        return d.level === level;
      }
      return true;
    })
    .filter(d => {
      if (!!isKyc1) {
        return d.isKyc1 === isKyc1;
      }
      return true;
    })
    .filter(d => {
      if (!!isKyc2) {
        return d.isKyc2 === isKyc2;
      }
      return true;
    });
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data,
      msg: "success"
    });
  }
  try {
    const body: any = {
      pageNo: p,
      pageSize: size
    };
    if (!!email) {
      body.email = email;
    }
    if (!!name) {
      body.nickname = name;
    }
    if (!!phone) {
      body.telephone = phone;
    }
    if (!!uid) {
      body.id = uid;
    }
    const newurl = `${config.beApi}/admin/user/getUserList`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          ...body
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    if (!!jsonRet.data && !!jsonRet.data.userList) {
      jsonRet.total = jsonRet.data.count;
      jsonRet.data = jsonRet.data.userList;
      jsonRet.data = jsonRet.data.map((d: any, index: number) => {
        return {
          code: index,
          uid: d.id,
          phone: d.telephone,
          email: d.email,
          enrollTime: new Date(d.createDate).getTime(),
          name: d.nickname,
          level: "0",
          isKyc1: "no",
          isKyc2: "no",
          status: d.status
        };
      });
    } else {
      jsonRet.data = [];
      jsonRet.total = 0;
    }
    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.get("/selectWithdraw", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { email, name, phone, uid, p, size, status } = req.query;
  const data: Array<any> = [
    {
      code: "1",
      createTime: 1542858853,
      phone: "13333333",
      email: "986177191@qq.com",
      uid: "0.00002552",
      coin: "BTC",
      amount: "0.01",
      recieveAmount: "0.01",
      passFee: "5",
      status: "1",
      arriveTime: 1542858853,
      passFeeRatio: "0.12",
      FirstCertRole: "dong",
      FirstCertTime: 1542858853,
      SecondCertRole: "dong",
      SecondCertTime: 1542858853,
      address: "sdlkjfklsdjfl",
      hash: "sdlkjflksdjflkds",
      failReason: "sdlkfjklsjfkl"
    },
    {
      code: "2",
      createTime: 1542858853,
      phone: "13333333",
      email: "986177191@qq.com",
      uid: "0.00002552",
      coin: "BTC",
      amount: "0.01",
      recieveAmount: "0.01",
      passFee: "5",
      status: "1",
      arriveTime: 1542858853,
      passFeeRatio: "0.12",
      FirstCertRole: "dong",
      FirstCertTime: 1542858853,
      SecondCertRole: "dong",
      SecondCertTime: 1542858853,
      address: "sdlkjfklsdjfl",
      hash: "sdlkjflksdjflkds",
      failReason: "sdlkfjklsjfkl"
    }
  ]
    .filter(d => {
      if (!!email) {
        return d.email.includes(email);
      }
      return true;
    })
    .filter(d => {
      if (!!uid) {
        return d.uid.includes(uid);
      }
      return true;
    });
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.beApi}/admin/review/search`;

    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          // email,
          // nickname: name,
          // telephone: phone,
          // userId: uid,
          pageNo: p,
          pageSize: size,
          state: status
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    if (!!jsonRet && !!jsonRet.data && !!jsonRet.data.list) {
      jsonRet.total = jsonRet.data.total;
      jsonRet.data = jsonRet.data.list;
      jsonRet.data = jsonRet.data.slice().map((d: any) => {
        // accountId: 4
        // high: null
        // modifytime: "2018-11-29T08:26:19.000+0000"
        // usedFee:
        return {
          code: "2",
          createTime: new Date(d.createtime).getTime(),
          phone: "13333333",
          email: "986177191@qq.com",
          uid: d.id,
          coin: "BTC",
          amount: "0.01",
          recieveAmount: d.amount,
          passFee: d.fee,
          status: String(d.state),
          arriveTime: 1542858853,
          passFeeRatio: "0.12",
          FirstCertRole: "dong",
          FirstCertTime: 1542858853,
          SecondCertRole: "dong",
          SecondCertTime: 1542858853,
          address: d.addressId,
          hash: d.transHash,
          failReason: "sdlkfjklsjfkl"
        };
      });
    } else {
      jsonRet.data = [];
      jsonRet.total = 0;
    }
    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

router.post("/saveWithdraw", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { id, status } = req.body;
  if (process.env.NODE_ENV === "eh") {
    res.json({
      code: 200,
      data: undefined,
      msg: "success"
    });
  }
  const newurl = `${config.beApi}/admin/review/operation`;
  try {
    const ret = await r(
      {
        url: newurl,
        body: JSON.stringify({
          operation: status,
          withdrawId: id
        })
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }
});

export default router;
